""" 用户密码加密
@Project: Rebar
@File: encryption.py
@Author: hzc
@Date: 2023/3/21 16:41
"""
import random
import string
import bcrypt


def create_authorization_num():
    """
    授权码生成器
    随机生成18位字符串
    :return:
    """
    random_list = []
    for i in range(18):
        random_list.append(random.choice(string.ascii_uppercase + string.digits))
    return ''.join(random_list)


def bcrypt_pwd(password: str):
    """
    密码加密, 随机生成盐
    :param password:
    :return:
    """
    salt = bcrypt.gensalt(10)  # 生成盐
    hashed_pwd = bcrypt.hashpw(password.encode("utf8"), salt)  # 加密后的密码
    return hashed_pwd


def verify_pwd(plaintext_password, hashed_password):
    """
    密码校验
    :param plaintext_password: 明文密码
    :param hashed_password: 加密后的密码
    :return:
    """
    plaintext_password = plaintext_password.encode('utf8')
    # 存入数据库的是str, 但是要的是byte类型 ===> asdf -> b'asdf'
    result = bcrypt.checkpw(plaintext_password, bytes(hashed_password, encoding='utf8'))
    return result


if __name__ == '__main__':
    print(verify_pwd("456", "$2b$10$RHLDXI3wk9sOrFQHLrtCf.NIXcEu2j46OzSsGQZK4g2E8hTx13k6m"))
    print(bcrypt_pwd("ADMINISTRATOR"))